package com.dzjcloud.dzj.common.mybatis;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dzjcloud.dzj.common.satoken.CurrentLogin;
import com.dzjcloud.dzj.common.satoken.entity.SatokenUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * <h3>springbootdemo</h3>
 * <p>创建时间、修改时间自动填充配置</p>
 *
 * @author : NiXiaoLong
 * @date : 2021.1.29
 **/
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {


    /**
     * 插入时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {


        //Date类型转LocalDateTime类型
        Date date = new Date();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);

        this.setFieldValByName("createTime", localDateTime, metaObject);
        //获取当前登录人
        String userId = (String) StpUtil.getLoginIdDefaultNull();
        this.setFieldValByName("createUserId", userId, metaObject);

    }

    /**
     * 更新时的填充策略
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        //Date类型转LocalDateTime类型
        Date date = new Date();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);


        this.setFieldValByName("updateTime", localDateTime, metaObject);
        //获取当前登录人
        String userId = (String) StpUtil.getLoginIdDefaultNull();
        this.setFieldValByName("updateUserId", userId, metaObject);
    }
}
